<template>
  <a-collapse-panel name="expandFields">
    <template #header>
      <collapse-title :title="$t('panel.expandFields')">
        <lucide-icon name="Info" />
      </collapse-title>
    </template>

    <edit-item :label="$t('panel.fieldName')">
      <a-input v-model:value="field.name" maxlength="32" @change="fieldName" />
    </edit-item>

    <edit-item :label="$t('panel.fieldValue')">
      <a-input v-model:value="field.string" maxlength="20" @change="fieldValue" />
    </edit-item>

    <a-button
      type="primary"
      class="inline-large-button"
      block
      @click="setElementExtensionField(-1)"
    >
      <span> {{ $t('panel.updateFieldsButton') }}</span>
    </a-button>
  </a-collapse-panel>
</template>
<script lang='ts'>
import { defineComponent } from 'vue'
import { mapState } from 'pinia'
import modelerStore from '@/store/modeler'
import EventEmitter from '@/utils/EventEmitter'
import { createModdleElement } from '@/utils/BpmnExtensionElementsUtil'
import editor from '@/store/editor'
export default defineComponent({
  name: 'ElementExtensionField',
  data() {
    return {
      fieldName: '',
      fieldValue: '',
      field: {
        name: '',
        string: ''
      },
      extensionElements: {},
      otherExtensionElements: []
    }
  },
  computed: {
    ...mapState(modelerStore, ['getActive', 'getActiveId', 'getModeling', 'getModdle'])
  },
  methods: {
    getElementExtensionField() {
      this.extensionElements = this.getActive.businessObject.get('extensionElements')
      this.otherExtensionElements = []
      this.extensionElements &&
        this.extensionElements.get('values').forEach((item) => {
          if (item.$type !== `${editor().getProcessEngine}:Field`) {
            this.otherExtensionElements.push(item)
          } else {
            this.field = { ...item }
          }
        })
    },
    setElementExtensionField() {
      const modeling = this.getModeling
      if (!this.extensionElements) {
        this.extensionElements = createModdleElement(
          'bpmn:ExtensionElements',
          { values: [] },
          this.getActive.businessObject
        )
        modeling?.updateModdleProperties(this.getActive, this.getActive.businessObject, {
          extensionElements: this.extensionElements
        })
      }

      const field = this.getModdle!.create(`${editor().getProcessEngine}:Field`, {
        name: this.field.name,
        string: this.field.string
      })
      modeling?.updateModdleProperties(this.getActive, this.extensionElements, {
        values: [...this.otherExtensionElements, field]
      })
    }
  },
  mounted() {
    this.getElementExtensionField()
    EventEmitter.on('element-update', this.getElementExtensionField)
  }
})
</script>
